# -*- coding: utf-8 -*-
import scrapy,re
from salve.items import BookItem
from scrapy_redis.spiders import RedisSpider

class BookSpider(RedisSpider):
    name = 'salve_book'
    #allowed_domains = ['book.douban.com']
    #start_urls = ['http://book.douban.com/']
    redis_key = "bookspider:start_urls"

    def __init__(self, *args, **kwargs):
        # Dynamically define the allowed domains list.
        domain = kwargs.pop('domain', '')
        self.allowed_domains = filter(None, domain.split(','))
        super(BookSpider, self).__init__(*args, **kwargs)

    def parse(self, response):
        item = BookItem()
        list = response.css("#wrapper")
        item['id'] = list.re_first('<div id="collect_form_([0-9]+)"></div>')
        item['title'] = list.re_first('<span property="v:itemreviewed">(.*?)</span>')
        info = list.css('#info').extract_first()
        #print(info)
        authors = re.search('<span.*?作者.*?</span>(.*?)<br>',info,re.S)
        if authors:
            item['author'] = '.'.join(re.findall('<a.*?>(.*?)</a>',authors.group(1),re.S))
        else:
            item['author'] = ' '
        item['press'] = ' '.join(re.findall('<span.*?出版社:</span>\s*(.*?)<br>',info,re.S))
        item['original'] = ' '.join(re.findall('<span.*?原作名:</span>\s*(.*?)<br>',info,re.S))
        translators = re.search('<span.*?译者.*?</span>(.*?)<br>',info,re.S)
        if translators:
            item['translator'] = '.'.join(re.findall('<a.*?>(.*?)</a>',translators.group(1),re.S))
        else:
            item['translator'] = ' '
        item['imprint'] = ' '.join(re.findall('<span.*?出版年:</span>\s*(.*?)<br>',info,re.S))
        item['pages'] = ' '.join(re.findall('<span.*?页数:</span>\s*(.*?)<br>',info))
        item['price'] = ' '.join(re.findall('<span.*?>定价:</span>\s*(.*?)<br>',info))
        item['binding'] = ' '.join(re.findall('<span.*?装帧:</span>\s*(.*?)<br>',info))
        item['series'] = ' '.join(re.findall('<span.*?丛书:</span>.*?<a.*?>(.*?)</a><br>',info))
        item['isbn'] = ' '.join(re.findall('<span.*?>ISBN:</span>\s*(.*?)<br>',info))
        #item['score'] = list.css('div.class="rating_logo"::text').extract_first
        item['score'] = '豆瓣评分:'.join(list.css('strong.rating_num::text').extract())
        item['number'] = ' '.join(list.css(".rating_people span::text").extract())
        #print(authors)
        # print(item)
        yield item